package com.hxkj.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;

/**
 * http request by okHttp3
 * created by kezhijie on 2018/8/24 9:27.
 * email to kezhijie@hxoss.com
 */
public class HttpClient {

    /**
     * GET请求
     * @param url
     * @param param
     */
    public static String docGet(String url, Map<String, Object> param) throws Exception {

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(resolveGetParam(url, param))
                .get()
                .build();

        Response response = client.newCall(request).execute();

        return response.body().string();
    }

    /**
     * POST请求
     * @param url
     * @param param
     * @return
     * @throws Exception
     */
    public static String doPost(String url, Map<String, Object> param) throws Exception {
        MediaType jsonType = MediaType.parse("application/json;charset=utf-8");
        String jsonString = JSON.toJSONString(param);
        RequestBody responseBody = RequestBody.create(jsonType, jsonString);

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .post(responseBody)
                .build();

        Response response = client.newCall(request).execute();

        return response.body().string();
    }

    private static String resolveGetParam(String url, Map<String, Object> param) {
        StringBuilder builder = new StringBuilder(url).append("?");
        for (Map.Entry<String, Object> map : param.entrySet()) {
            builder.append(map.getKey()).append("=").append(map.getValue());
        }
        return builder.toString();
    }
}
